﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Caching;

namespace PJ.Data
{
    /// <summary>
    /// ObjectPICProvider : Persist In Cache data provider
    /// </summary>
    /// <typeparam name="I">Object to provide interface type</typeparam>
    /// <typeparam name="C">Object to provide concrete class type</typeparam>
    public abstract class ItemPICProvider<I, C> : EntityPICProvider<I, C>, IItemProvider<I>
        where C : BaseItemData, I, new()
        where I : class, IItemData
    {
        public ItemPICProvider(ICacheManager cache) : base(cache)
        {
        }

        public I GetByName(string name, GetDataMode mode)
        {
            if (name == null && name.Length == 0)
                throw new ArgumentNullException();
            I entity = (from d in DataObjects.Values where d.Name == name select d as I).SingleOrDefault();
            if (entity == null && (mode & GetDataMode.Find) != GetDataMode.Find)
                throw new DataNotFoundException("name", name);
            else
                return entity;
        }

        public I GetByAlias(string aliasName, GetDataMode mode)
        {
            if (aliasName == null || aliasName == "")
                throw new ArgumentNullException("aliasName");
            I entity = (from d in DataObjects.Values where d.AliasName == aliasName select d as I).SingleOrDefault();
            if (entity == null && (mode & GetDataMode.Find) != GetDataMode.Find)
                throw new DataNotFoundException("aliasName", aliasName);
            else
                return entity;
        }


        public string[] Search(string searchText, GetDataMode mode)
        {
            if (searchText == null || searchText == "")
                throw new ArgumentNullException("searchText");
            List<string> list = new List<string>();
            foreach (IItemData data in DataObjects.Values)
            {
                if (data.Id.Contains(searchText) || data.Name.Contains(searchText) || data.AliasName.Contains(searchText))
                    list.Add(data.GlobalId);
            }
            if (list.Count == 0)
                if ((mode & GetDataMode.Find) != GetDataMode.Find)
                    throw new DataNotFoundException("searchText", searchText);
                else
                    return null;
            else
                return list.ToArray();
        }


        #region Interface override
        IItemData IItemProvider.GetByName(string name, GetDataMode mode)
        {
            return GetByName(name, mode);
        }


        IItemData IItemProvider.GetByAlias(string aliasName, GetDataMode mode)
        {
            return GetByAlias(aliasName, mode);
        }


        #endregion

    }
}
